import { constantRoutes, asyncRoutes } from '@/router'
import { Permission } from '../interface/permission'
import { ActionContext } from 'vuex'
import { Dictionary, RouteConfig } from 'vue-router/types/router'
type RoutesSetting = Permission['routes']
// type RouteType = RoutesSetting[number]
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// function hasPermission(roles: string[], route: RouteType) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta?.roles.includes(role))
//   } else {
//     return true
//   }
// }

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes: RoutesSetting, roles: Dictionary<Dictionary<string>>) {
  const res: RoutesSetting = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (!tmp.meta?.permission || resolveUserPermission(tmp.meta?.permission, roles)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

function resolveUserPermission(
  permission: string | undefined,
  roles: Dictionary<Dictionary<string>>
) {
  if (permission === undefined) return true
  const curr = roles[permission]
  if (!curr) return true
  if (Object.values(curr).every(item => item === '0')) return false
  return true
}

const state: Permission = {
  // 通用路由 与 新增路由拼合
  routes: [],
  // 基于登录用户的权限新增的路由配置
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state: Permission, routes: RoutesSetting) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // roles: 存储用户所有权限的数组
  generateRoutes(
    { commit }: ActionContext<Permission, any>,
    roles: Dictionary<Dictionary<string>>
  ) {
    return new Promise(resolve => {
      let accessedRoutes: RouteConfig[]
      if (!roles) accessedRoutes = []
      else accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
